<template>
    <el-dialog
        class="custom-modal"
        :title="title"
        :visible.sync="show"
        append-to-body
        top="20vh"
        @open="_open"
        @close="_close"
        @closed="_afterClose"
        v-auto-focus
        width="540px">
        <div class="content">
            <div class="item" v-for="(item, index) in allList" :key="item.key">
                <span class="num">{{ index + 1 }}</span>
                <el-cascader
                    class="cascader-set-only"
                    ref="cascader"
                    v-model="item.labelList"
                    :options="options"
                    :props="props"
                    collapse-tags
                    clearable>
                </el-cascader>
                <i class="el-icon-plus opera-btn" @click="addItem(index)"></i>
                <i class="el-icon-minus opera-btn" @click="delItem(index)"></i>
            </div>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="close">取消</el-button>
            <el-button class="sure" type="primary" @click="sure" :loading="ajaxLoader">提交</el-button>
        </div>
    </el-dialog>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { getRandomId } from "@/utils";

@Component
export default class DragOptionForm extends Vue {
    title = "";
    show = false;
    ajaxLoader = false;
    ajaxIndex = 0;

    typeId = ""
    // 当前可用选项
    options: any[] = []
    // 当前设置节点
    currentNode: any = {}
    // 所有唯一性
    allList: any[] = []
    // 所有选中过的唯一性分类id（回显时使用）
    allTypeId: any[] = []

    get props() {
        return {
            value: "id",
            label: "name",
            multiple: true,
            lazy: true,
            lazyLoad: async(node: any, resolve: any) => {
                if (node.children.length) {
                    resolve([]);
                } else {
                    const res: any = await this.getOptions(node);
                    resolve(res);
                }
            }
        };
    }

    async _open() {
        this.$emit("onopen");
        this.getDefaultValue();
    }

    _close() {
        this.$emit("onclose");
    }

    _afterClose() {
        this.$nextTick(function() {
            this.$emit("onafterclose");
            this.$el.remove && this.$el.remove();
        });
    }

    loader(state: boolean) {
        if (state) {
            if (this.ajaxIndex === 0) this.ajaxLoader = true;
            this.ajaxIndex++;
        } else {
            setTimeout(() => {
                this.ajaxIndex--;
                if (this.ajaxIndex === 0) this.ajaxLoader = false;
            }, 300);
        }
    }

    close() {
        this.show = false;
        this.$emit("close");
    }

    async sure() {
        const data: any[] = [];
        this.allList.forEach((item: any) => {
            const itemData = item.labelList.map((it: any) => {
                return {
                    labelId: it[it.length - 1],
                    typeId: it[it.length - 2]
                };
            });
            data.push({
                uniqueIndexVoList: itemData,
                typeId: this.typeId
            });
        });
        const res = await this.$server["business/setOnly"]({
            data
        });
        if (res.data.code === 200) {
            this.$message.success("设置成功");
            this.show = false;
            this.$emit("sure", this.typeId);
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    async getDefaultValue() {
        this.allList = [];
        this.allTypeId = [];
        const res = await this.$server["business/getOnly"]({
            data: {
                typeId: this.typeId
            }
        });
        if (res.data.code === 200) {
            if (res.data.data && res.data.data.length) {
                res.data.data.forEach((item: any) => {
                    this.allList.push({
                        labelList: item.map((it: any) => {
                            this.allTypeId.push(it.typeId);
                            return [it.typeId, it.labelId];
                        }),
                        key: getRandomId()
                    });
                });
                this.allTypeId = Array.from(new Set(this.allTypeId));
            } else {
                this.allList = [{
                    labelList: [],
                    key: getRandomId()
                }];
            }
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
        this.getOptions();
    }

    async getOptions(node?: any) {
        if (node) {
            if (node.level === 2) return [];
            let nodes: any[] = [];
            if (node.data.field === "basic") {
                nodes = [{
                    id: -1,
                    name: "采集区域",
                    leaf: true
                }];
            }
            const res = await this.$server["business/getTable"]({
                data: {
                    keyword: "",
                    valueKindId: "",
                    pageSize: 99999,
                    currentPage: 1,
                    typeId: node.data.id
                }
            });
            if (res.data.code === 200) {
                const list = res.data.data.records.map((item: any) => {
                    return {
                        id: item.id,
                        name: item.name,
                        leaf: true
                    };
                });
                nodes = nodes.concat([], list);
            } else {
                this.$message.error(res.data.message || "接口请求错误!");
            }
            return nodes;
        } else {
            this.options = JSON.parse(JSON.stringify(this.currentNode.children));
            for (const item of this.options) {
                item.children = await this.getOptions({
                    data: {
                        id: item.id,
                        field: item.field
                    }
                });
            }
        }
    }

    addItem(index: number) {
        this.allList.splice(index + 1, 0, {
            labelList: [],
            key: getRandomId()
        });
    }

    delItem(index: number) {
        this.allList.splice(index, 1);
        if (!this.allList.length) {
            this.allList = [{
                labelList: [],
                key: getRandomId()
            }];
        }
    }
}
</script>
<style scoped lang="scss">
.custom-modal {
    margin: 0;
    & /deep/ {
        .el-dialog {
            width: 4.5rem;
        }
        .custom-form .cf__group .el-textarea.el-input--medium,
        .custom-form .cf__group .el-date-editor.el-input,
        .custom-form .cf__group .el-textarea.el-input--medium .el-textarea__inner,
        .custom-form .cf__group .el-input--medium .el-input__inner{
            width: 100%;
        }
    }
    .cascader-set-only {
        width: 380px;
        margin: 0 8px;
    }
    .title {
        margin: 4px 0 8px 0;
    }
    .item {
        @include flexLayout(flex,normal,center);
        margin-bottom: 10px;
        &:last-child {
            margin-bottom: 0;
        }
        .num {
            display: inline-block;
            width: 24px;
            height: 24px;
            line-height: 22px;
            border: 1px solid #666;
            border-radius: 12px;
            text-align: center;
            color: #666;
            font-size: 18px;
        }

        .opera-btn {
            font-size: 20px;
            color: #333;
            padding: 4px;
        }
    }

    .content {
        max-height: 400px;
        overflow-y: auto;
    }
}
</style>
